package com.estock.platform.reader;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.estock.common.model.security.DailyTrans;
import com.estock.common.util.FileUtil;
import com.estock.common.util.StringUtil;

public class YahooCsvReader extends AbstractDataReader<DailyTrans> {
	
	protected static final String COMMA = ",";
	protected static final String KEY_CODE = "Code";
	
	protected static final String KEY_DATE = "Date";
    protected static final String KEY_OPEN = "Open";
    protected static final String KEY_HIGH = "High";
    protected static final String KEY_LOW = "Low";
    protected static final String KEY_CLOSE = "Close";
    protected static final String KEY_VOLUME = "Volume";
    protected static final String KEY_ADJ_CLOSE = "Adj Close";
	
	@Override
	public List<DailyTrans> read(String fileName) {
		List<DailyTrans> results = new ArrayList<DailyTrans>();
		
		BufferedReader reader = null;
		try {
			String readString = FileUtil.readString(fileName, FileUtil.CHARSET_UTF8);
			reader = new BufferedReader(new StringReader(readString));
			// neglect first row
			reader.readLine(); 
			
			String line = reader.readLine();
			while (line != null) {
                if (StringUtil.isEmpty(line)) return new ArrayList<DailyTrans>();
                
                String[] values = line.split(COMMA);
                DailyTrans dailyTrans = new DailyTrans();
                // get 000625 from .../.../000625.csv
                dailyTrans.setCode(fileName.substring(fileName.length() - 10, fileName.length() - 4));
                dailyTrans.setsDate(StringUtil.parseDate(values[columnIndex(KEY_DATE)]));
                dailyTrans.setOpenPrice(StringUtil.parseDouble(values[columnIndex(KEY_OPEN)]));
                dailyTrans.setHighPrice(StringUtil.parseDouble(values[columnIndex(KEY_HIGH)]));
                dailyTrans.setLowPrice(StringUtil.parseDouble(values[columnIndex(KEY_LOW)]));
                dailyTrans.setClosePrice(StringUtil.parseDouble(values[columnIndex(KEY_CLOSE)]));
                dailyTrans.setAdjClosePrice(StringUtil.parseDouble(values[columnIndex(KEY_ADJ_CLOSE)]));
                dailyTrans.setVolume(StringUtil.parseLong(values[columnIndex(KEY_VOLUME)]));
                
                results.add(dailyTrans);
                line = reader.readLine();
			}
		} catch (Exception e) {
			throw new RuntimeException("Error in reading file: " + fileName);
		}
		
		return results;
		
	}

	@SuppressWarnings("serial")
	@Override
	protected Map<String, Integer> createCsvMapping() {
		return new HashMap<String, Integer>(){{
			put(KEY_DATE, 0);
			put(KEY_OPEN, 1);
			put(KEY_HIGH, 2);
			put(KEY_LOW, 3);
		  	put(KEY_CLOSE, 4);
		  	put(KEY_VOLUME, 5);
		 	put(KEY_ADJ_CLOSE, 6);
		}};
	}

}
